import datetime
import logging
import sys

from check import *
import util


__author__  = 'ZL <837806295@qq.com>'
__product__ = 'main'
__version__ = '3.1.0'
__date__    = '2023/04/08'


log = logging.getLogger(__product__)


def set_log():
    config = log_config()
    if config is None:
        log.addHandler(logging.NullHandler())
        util.prompt('Log off')
    else:
        util.set_log(__file__, *config)

def main():
    try:
        parse_command_line()
    except Exception:
        log.exception('main ... exception | exception')
        return 1
    except SystemExit as e:
        return (1 if e.code >= 128 or e.code < 0 else e.code)
    except KeyboardInterrupt:
        log.exception('main ... exception | keyboardinterrupt')
        return 1

    baseline = datetime.datetime.now()

    try:
        set_log()

        util.prompt_startup(baseline)

        init()
        schedule_tasks()
        clean()
    except Exception:
        log.exception('main ... exception | exception')
        util.prompt_terminate(baseline, 1)
        return 1
    except SystemExit as e:
        if e.code:
            log.exception('main ... exception | systemexit, exit code: %d',
                          e.code)
            exit_code = (1 if e.code >= 128 or e.code < 0 else e.code)
            util.prompt_terminate(baseline, exit_code)
            return exit_code
    except KeyboardInterrupt:
        log.exception('main ... exception | keyboardinterrupt')
        util.prompt_terminate(baseline, 1)
        return 1

    util.prompt_terminate(baseline)
    return 0


if __name__ == '__main__':
    exit_code = main()
    if exit_code:
        sys.exit(exit_code)
